package com.ljpz.web.service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljpz.common.httpclient.HttpResult;
import com.ljpz.common.service.ApiService;
import com.ljpz.sso.query.bean.User;
import com.ljpz.web.bean.Order;
import com.ljpz.web.bean.PageResult;
import com.ljpz.web.threadLocal.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

/**
 * 提交订单到订单系统
 *
 *
 * Created by liujunchen on 2016/12/23.
 */
@Service
public class OrderService {
    @Autowired
    private  ApiService apiService   ;
    private  static  final ObjectMapper  MAPPER = new ObjectMapper()  ;
    @Value("${LJPZ_ORDER_URL}")
    private  String   LJPZ_ORDER_URL ;
    public String submit(Order order) {
        String url =LJPZ_ORDER_URL+"/order/create" ;
        try {
            HttpResult httpResult  = this.apiService.doPostJson(url,MAPPER.writeValueAsString(order));
            if (httpResult.getCode().intValue()==200){
                String body = httpResult.getBody() ;
                JsonNode jsonNode  = MAPPER.readTree(body) ;
                if (jsonNode.get("status").asInt()==200){
                    //提交成功
                    return  jsonNode.get("data").asText();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  null;
    }

    public Order queryByOrderId(String orderId) {
        String   url = LJPZ_ORDER_URL+"/order/query"+orderId  ;
        try {
            String jsonData  = this.apiService.doGet(url) ;
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(jsonData)){
                return   MAPPER.readValue(jsonData,Order.class) ;
            }
        } catch (Exception   e) {
            e.printStackTrace();
        }
        return  null    ;
    }

    /**
     * 查询页数
     * @param page 每页显示数量
     *
     *
     * @param count 总条数
     * @return
     */
    public PageResult<Order> queryByUserId(Integer page , Integer count ) {
        //当前用户值
        User user  = UserThreadLocal.get();
        String buyerNick = user.getUsername()  ;
        //请求访问地址
        String  url  = LJPZ_ORDER_URL+"/order/query/"+buyerNick+"/"+ page.toString()+"/"+count.toString();
        try {
            String jsonData= this.apiService.doGet(url)  ;
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(jsonData)){
                return  MAPPER.readValue(jsonData, PageResult.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null ;
    }
}
